package com.eat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.eat.constant.MessageConstant;
import com.eat.context.BaseContext;
import com.eat.dto.*;
import com.eat.entity.*;
import com.eat.exception.AddressBookBusinessException;
import com.eat.exception.OrderBusinessException;
import com.eat.exception.ShoppingCartBusinessException;
//import com.eat.mapper.*;
import com.eat.result.PageResult;
import com.eat.mapper.*;
import com.eat.service.OrderService;
import com.eat.utils.WeChatPayUtil;
import com.eat.vo.OrderPaymentVO;
import com.eat.vo.OrderStatisticsVO;
import com.eat.vo.OrderSubmitVO;
import com.eat.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImp implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 用户下单
     * @param submitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO submitDTO) {

        //处理业务异常情况
        AddressBook byId = addressBookMapper.getById(submitDTO.getAddressBookId());
        if(byId == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        Long currentId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(currentId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        //判断购物车是否为空
        if(list == null || list.size()==0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //开始插入订单数据
        Orders order =new Orders();
        BeanUtils.copyProperties(submitDTO,order);

        order.setOrderTime(LocalDateTime.now());
        order.setPayStatus(Orders.UN_PAID);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setPhone(byId.getPhone());
        order.setUserId(currentId);

        orderMapper.insert(order);
        //构造订单详细list
        List<OrderDetail> orderDetailList =new ArrayList<>();
        for (ShoppingCart cart : list) {
          OrderDetail orderDetail = new OrderDetail();
          BeanUtils.copyProperties(cart,orderDetail);
          orderDetail.setOrderId(order.getId());
          orderDetailList.add(orderDetail);
        }
        //添加订单详细信息
        orderDetailMapper.insertBatch(orderDetailList);
        //清空购物车
        shoppingCartMapper.deleteByUserId(currentId);

        OrderSubmitVO build = OrderSubmitVO.builder()
                .id(order.getId())
                .orderTime(order.getOrderTime())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .build();

        return build;
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        Map map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号："+outTradeNo);
        String s = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(s);

    }

    /**
     * 查询订单
     * @param id
     * @return
     */
    @Override
    public Orders getOrder(Long id) {

        Orders orders =  orderMapper.getOrder(id);

        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetail(id);

        orders.setOrderDetailList(orderDetailList);

        return orders;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void delete(Long id) {

        orderMapper.delete(id);

    }
    /**
     * 历史订单查询
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult page(Integer page, Integer pageSize, Integer status) {

        PageHelper.startPage(page,pageSize);

        Page<Orders> orders = orderMapper.page(status);
        for (Orders order : orders) {
            List<OrderDetail> orderDetail = orderDetailMapper.getOrderDetail(order.getId());
            order.setOrderDetailList(orderDetail);
        }
        return new PageResult(orders.getTotal(),orders.getResult());
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void againOrder(Long id) {

        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetail(id);
        //删除购物车的其他商品
        Long currentId = BaseContext.getCurrentId();
        shoppingCartMapper.deleteByUserId(currentId);
        //开始
        List<ShoppingCart> shoppingCarts =new ArrayList<>();

        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);

            shoppingCart.setUserId(currentId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            shoppingCarts.add(shoppingCart);
        }

        shoppingCartMapper.againOrder(shoppingCarts);

    }

    /**
     * 催单
     * @param id
     */
    @Override
    public void reminderOrder(Long id) {

        Orders order = orderMapper.getOrder(id);
        if (order==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map=new HashMap<>();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号："+order.getNumber());

        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }

    /**
     * 分页查询订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult getPage(OrdersPageQueryDTO ordersPageQueryDTO) {

        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        Page<Orders> orders = orderMapper.getPage(ordersPageQueryDTO);

        return new PageResult(orders.getTotal(),orders.getResult());
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {

        Orders build = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();

        orderMapper.update(build);

    }

    /**
     * 订单派送
     * @param id
     */
    @Override
    public void delivery(Long id) {

        Orders build = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();

        orderMapper.update(build);

    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
            //以下为支付功能暂未开发完全；暂不运行
//        Orders ordersDB = orderMapper.getOrder(ordersRejectionDTO.getId());
//        Integer payStatus = ordersDB.getPayStatus();
//        if (payStatus == Orders.PAID) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
//        }

        Orders build = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .build();

        orderMapper.update(build);

    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {

        Orders build = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .build();

        orderMapper.update(build);

    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {

        Orders order = orderMapper.getOrder(ordersCancelDTO.getId());

        if(order.getStatus() == Orders.COMPLETED){
            throw new OrderBusinessException("订单已完成不可取消");
        }

        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {

        Integer cs1 = orderMapper.getStatistics(Orders.TO_BE_CONFIRMED);
        Integer cs2 = orderMapper.getStatistics(Orders.CONFIRMED);
        Integer cs3 = orderMapper.getStatistics(Orders.DELIVERY_IN_PROGRESS);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(cs2);
        orderStatisticsVO.setDeliveryInProgress(cs3);
        orderStatisticsVO.setToBeConfirmed(cs1);

        return orderStatisticsVO;
    }


}
